/**
 * 快速接入钉钉扫码登陆二维码显示
 * 定义window方法DDLogin
 * @appid 钉钉开放平台appkey
 * @el 显示二维码页面元素id
 * @width 二维码宽度
 * @height 二维码高度
 */
!(function (window, document) {
  function d(a) {
    var e,
      c = document.createElement('iframe'),
      d = 'https://login.dingtalk.com/login/qrcode.htm?goto=' + a.goto;
    (d += a.style ? '&style=' + encodeURIComponent(a.style) : ''),
      (d += a.href ? '&href=' + a.href : ''),
      (c.src = d),
      (c.frameBorder = '0'),
      (c.allowTransparency = 'true'),
      (c.scrolling = 'no'),
      (c.width = a.width ? a.width + 'px' : '365px'),
      (c.height = a.height ? a.height + 'px' : '400px'),
      (e = document.getElementById(a.id)),
      (e.innerHTML = ''),
      e.appendChild(c);
  }
  window.DDLogin = function ({
    appid = '',
    el,
    width = '260',
    height = '380',
  }) {
    if (!appid || !el) {
      alert('缺少必需字段appid或el');
    }
    // 钉钉登录
    var url = encodeURIComponent(window.location.href);
    // 测试
    // var goto = 'https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=dingoao18fpsm90erp4x0y&response_type=code&scope=snsapi_login&state=STATE&redirect_uri='+url
    // 正式
    var goto =
      'https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=' +
      appid +
      '&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=' +
      url;

    d({
      id: el, //这里需要你在自己的页面定义一个HTML标签并设置id，例如<div id="login_container"></div>或<span id="login_container"></span>
      goto: encodeURIComponent(goto), //请参考注释里的方式
      style: 'border:none;background-color:transparent;',
      width,
      height,
    });
    var handleMessage = function (event) {
      var origin = event.origin;
      if (origin == 'https://login.dingtalk.com') {
        //判断是否来自ddLogin扫码事件。
        var loginTmpCode = event.data; //拿到loginTmpCode后就可以在这里构造跳转链接进行跳转了
        if (loginTmpCode) {
          const getUrl = `${goto}&loginTmpCode=${loginTmpCode}`;
          window.location.href = getUrl;
        }
      }
    };
    if (typeof window.addEventListener != 'undefined') {
      window.addEventListener('message', handleMessage, false);
    } else if (typeof window.attachEvent != 'undefined') {
      window.attachEvent('onmessage', handleMessage);
    }
  };
})(window, document);
